# Definition for a Node.
class Node:
    def __init__(self, val, left, right, next):
        self.val = val
        self.left = left
        self.right = right
        self.next = next


class Solution:
    def connect(self, root: Node) -> Node:
        if root:
            self.search([root])
        return root

    def search(self, list_in):
        search_list = []
        for note in list_in:
            if note.left:
                search_list.append(note.left)
            if note.right:
                search_list.append(note.right)
        for i in range(len(list_in) - 1):
            list_in[i].next = list_in[i + 1]
        if search_list:
            self.search(search_list)
